package mp

import (
	"context"
	"errors"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	xb "xorm.io/builder"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type LessonSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLessonSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LessonSaveLogic {
	return &LessonSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LessonSaveLogic) LessonSave(req *types.LessonReq) (resp string, err error) {
	course := &models.Course{Id: req.CourseId}
	has := db.GetData(course)
	if !has {
		return "", errors.New("课程不存在")
	}
	data := &models.Lesson{}
	copier.Copy(data, req)

	if course.Type == 10 {
		if req.ChapterId == 0 {
			return "", errors.New("请选择章节")
		}
		chapter := &models.Chapter{Id: req.ChapterId}
		has := db.ExistData(chapter)
		if !has {
			return "", errors.New("章节不存在")
		}
	} else {
		lesson := &models.Lesson{CourseId: req.CourseId}
		has := db.ExistData(lesson)
		if has && req.Id == 0 {
			return "", errors.New("单视频课程，只能添加一个内容")
		}
		data.ChapterId = 0
	}

	if req.Id == 0 {
		db.InsertData(data)
	} else {
		db.UpdateData(data, xb.Eq{"id": req.Id})
	}

	return "操作成功", nil
}
